﻿namespace Microsoft.VisualStudio.ServiceModel.DomainServices.Tools
{
    using System;
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    using System.Reflection;

    internal class LinqToSqlEntity : BusinessLogicEntity
    {
        private bool _hasTimestampMember;
        private string _tablePropertyName;

        public LinqToSqlEntity(LinqToSqlContext context, MetaType metaType) : base(context, metaType.Name, metaType.Type)
        {
            this._hasTimestampMember = metaType.VersionMember != null;
        }

        private string FindTablePropertyName()
        {
            foreach (PropertyInfo info in base.BusinessLogicContext.ContextType.GetProperties())
            {
                Type propertyType = info.PropertyType;
                if (propertyType.IsGenericType)
                {
                    Type[] genericArguments = propertyType.GetGenericArguments();
                    if (((genericArguments.Length == 1) && !(base.ClrType != genericArguments[0])) && !(propertyType.GetGenericTypeDefinition() != typeof(Table<>)))
                    {
                        return info.Name;
                    }
                }
            }
            return null;
        }

        public override bool CanBeIncluded
        {
            get
            {
                return ((this.TablePropertyName != null) && base.CanBeIncluded);
            }
        }

        public bool HasTimestampMember
        {
            get
            {
                return this._hasTimestampMember;
            }
        }

        public string TablePropertyName
        {
            get
            {
                if (this._tablePropertyName == null)
                {
                    this._tablePropertyName = this.FindTablePropertyName();
                }
                return this._tablePropertyName;
            }
        }
    }
}

